<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
			<el-form-item label="企业名称" prop="companyName">
				<el-input
					v-model="queryParams.companyName"
					placeholder="请输入企业名称"
					clearable
					style="width: 200px"
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item label="法人姓名" prop="legalPerson">
				<el-input
					v-model="queryParams.legalPerson"
					placeholder="请输入法人姓名"
					clearable
					style="width: 200px"
					@keyup.enter="handleQuery"
				/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
				<el-button icon="Refresh" @click="resetQuery">重置</el-button>
				<div ref="qrCodeRef" style="display: none"></div>
			</el-form-item>
		</el-form>

		<el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="序号" align="center" prop="id" width="100" />
			<el-table-column label="企业名称" align="center" prop="companyName" />
			<el-table-column label="法人姓名" align="center" prop="legalPerson" />
			<el-table-column label="统一社会信用代码" align="center" prop="companyNo" />
			<el-table-column label="银行卡号" align="center" prop="bankNo" />
			<el-table-column label="开户行" align="center" prop="bankName" />
			<el-table-column label="银行预留手机号码" align="center" prop="bankPhone" />
			<el-table-column label="金额（万元）" align="center" prop="quotaAmount" />
			<el-table-column label="录入人" align="center" prop="createBy" />
			<el-table-column label="创建时间" align="center" prop="createTime" width="100">
				<template #default="scope">
					<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template #default="scope">
					<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改企业测额信息对话框 -->
		<el-dialog :title="title" v-model="open" width="780px" append-to-body>
			<el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
				<el-form-item label="企业名称" prop="companyName">
					<el-input v-model="form.companyName" placeholder="请输入企业名称" />
				</el-form-item>
				<el-form-item label="法人姓名" prop="legalPerson">
					<el-input v-model="form.legalPerson" placeholder="请输入法人姓名" />
				</el-form-item>
				<el-form-item label="统一社会信用代码" prop="companyNo">
					<el-input v-model="form.companyNo" placeholder="请输入统一社会信用代码" />
				</el-form-item>
				<el-form-item label="银行卡号" prop="bankNo">
					<el-input v-model="form.bankNo" placeholder="请输入银行卡号" />
				</el-form-item>
				<el-form-item label="开户行" prop="bankName">
					<el-input v-model="form.bankName" placeholder="请输入开户行" />
				</el-form-item>
				<el-form-item label="银行预留手机号码" prop="bankPhone">
					<el-input v-model="form.bankPhone" placeholder="请输入银行预留手机号码" />
				</el-form-item>
				<el-form-item label="金额（万元）" prop="quotaAmount">
					<el-input-number
						step="0.01" :controls="false" v-model="form.quotaAmount" placeholder="请输入金额" style="width: 100%"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import * as api from '@/api/quota/companyInfo';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCurrentInstance, h, reactive, ref, toRefs } from 'vue';

const { proxy } = getCurrentInstance();

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const qrCodeRef = ref();

const data = reactive({
	form: {},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		companyName: undefined,
		legalPerson: undefined
	},
	rules: {
		companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
		quotaAmount: [{ required: true, message: '金额不能为空', trigger: 'change' }]
	}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业测额信息列表 */
function getList() {
	loading.value = true;
	api.list(queryParams.value).then(response => {
		dataList.value = response.rows;
		total.value = response.total;
		loading.value = false;
	});
}

/** 取消按钮 */
function cancel() {
	open.value = false;
	reset();
}

/** 表单重置 */
function reset() {
	form.value = {
		companyName: undefined,
		quotaAmount: undefined
	};
	proxy.resetForm('formRef');
}

/** 搜索按钮操作 */
function handleQuery() {
	queryParams.value.pageNum = 1;
	getList();
}

/** 重置按钮操作 */
function resetQuery() {
	proxy.resetForm('queryRef');
	handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
	ids.value = selection.map(item => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加企业测额信息';
}

/**修改按钮操作 */
function handleUpdate(row) {
	reset();
	const id = row.id || ids.value;
	api.get(id).then(response => {
		form.value = response.data;
		open.value = true;
		title.value = '修改企业测额信息';
	});
}

/** 提交按钮 */
function submitForm() {
	proxy.$refs['formRef'].validate(valid => {
		if (valid) {
			if (form.value.id !== undefined) {
				api.update(form.value).then(response => {
					proxy.$modal.msgSuccess('修改成功');
					open.value = false;
					getList();
				});
			} else {
				api.add(form.value).then(response => {
					proxy.$modal.msgSuccess('新增成功');
					open.value = false;
					getList();
				});
			}
		}
	});
}

/** 删除按钮操作 */
function handleDelete(row) {
	const idList = row.id || ids.value;
	proxy.$modal.confirm('是否确认删除企业测额信息编号为"' + idList + '"的数据项？').then(function() {
		return api.remove(idList);
	}).then(() => {
		getList();
		proxy.$modal.msgSuccess('删除成功');
	}).catch(() => {});
}

async function handleQrCode() {
	qrCodeRef.value.innerHTML = '';
	// const { id } = await api.getQrCodeId()
	const id = 32;
	const url = `https://www.baidu.com/${ id }`;

	new QRCode(qrCodeRef.value, {
		text: url,
		width: 128,
		height: 128,
		colorDark: '#000000',
		colorLight: '#ffffff',
		correctLevel: QRCode.CorrectLevel.H
	});

	const canvas = qrCodeRef.value.querySelector('canvas');
	// 将 Canvas 转换为 Data URL
	const dataURL = canvas.toDataURL();

	ElMessageBox({
		title: '测额二维码',
		showCancelButton: true,
		cancelButtonText: '复制二维码',
		confirmButtonText: '复制链接',
		message: h('p', {
			style: 'display: flex; align-items: center;'
		}, [
			h('img', { src: dataURL }),
			h('span', { style: 'margin-left: 10px;' }, url)
		])
	}).then(res => {
		// 复制url到剪切板
		navigator.clipboard.writeText(url).then(() => {
			ElMessage({
				message: '链接已复制',
				type: 'success'
			});
		}).catch(() => {
			console.error('链接复制失败');
		});
	}).catch(() => {
		// 创建一个 Blob 对象
		const blob = dataURLToBlob(dataURL);
		navigator.clipboard
			.write([new ClipboardItem({ 'image/png': blob })])
			.then(() => {
				ElMessage({
					message: '二维码已复制',
					type: 'success'
				});
			})
			.catch(() => {
				console.error('二维码复制失败');
			});
	});
}

function dataURLToBlob(dataURL) {
	const arr = dataURL.split(',');
	const mime = arr[0].match(/:(.*?);/)[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
}

getList();
</script>

<style scoped lang="less">
.el-input-number {
	::v-deep(.el-input__inner) {
		text-align: left;
	}
}
</style>
